using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using AFI.Speargun.Web.Core;
using AFI.Speargun.Web.Models;
using System.Web.Security;

namespace AFI.Speargun.Web.Controllers
{
    public class AssetInventoryController : BaseController
    {
        //
        // GET: /AssetInventory/Index/{id}

        [Authorize]
        public ActionResult Index(Guid id)
        {
            var assetEntry = _service.GetAssetEntry(id);

            ViewData["AssetEntry.Appellation"] = assetEntry.Appellation;
            ViewData["AssetEntryId"] = id;

            if (!assetEntry.AssetInventory.IsLoaded)
                assetEntry.AssetInventory.Load();

            return View(assetEntry.AssetInventory);
        }

        //
        // GET: /AssetInventory/Details/{id}

        [Authorize]
        public ActionResult Details(Guid id)
        {
            var assetInventory = _service.GetAssetInventory(id);

            if (!assetInventory.AssetEntryReference.IsLoaded)
                assetInventory.AssetEntryReference.Load();

            ViewData["AssetEntry.Appellation"] = assetInventory.AssetEntry.Appellation;
            ViewData["AssetEntryId"] = id;

            return View(assetInventory);
        }

        //
        // GET: /AssetInventory/Create/{id}

        [Authorize]
        public ActionResult Create(Guid id)
        {
            this.BuildViewData(String.Empty, String.Empty);
            var assetEntry = _service.GetAssetEntry(id);

            ViewData["AssetEntry.Appellation"] = assetEntry.Appellation;
            ViewData["AssetEntryId"] = id;

            return View();
        }

        //
        // POST: /AssetInventory/Create/{id}

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Create(Guid id, AssetInventory assetInventory)
        {
            assetInventory.CheckingUser = (Guid)Membership.GetUser().ProviderUserKey;

            if (_service.CreateAssetInventory(id, assetInventory))
                return RedirectToAction("Details", new { id = assetInventory.AssetInventoryId });

            this.BuildViewData(
                ((DepreciationMode)assetInventory.AssetStatus).GetTextValue(),
                ((CheckingResult)assetInventory.Result).GetTextValue()
                );
            var assetEntry = _service.GetAssetEntry(id);

            ViewData["AssetEntry.Appellation"] = assetEntry.Appellation;
            ViewData["AssetEntryId"] = id;

            return View();
        }

        void BuildViewData(string selectedAssetStatus, string selectedCheckingResult)
        {
            ViewData["AssetStatus"] = SelectListBuilder.Create(typeof(AssetStatus), selectedAssetStatus);
            ViewData["Result"] = SelectListBuilder.Create(typeof(CheckingResult), selectedCheckingResult);
        }
    }
}
